<template>
  <div class="mod-category">
    <h1>分类管理</h1>
    <el-row v-show="saveShow">
      <el-button type="primary" round @click="save">保存修改</el-button>
      <el-button round @click="cancel">取消</el-button>
    </el-row>
    <el-button type="danger" plain @click="deleteBatch">批量删除按钮</el-button>
    <el-tree
      show-checkbox
      :data="tree"
      :props="defaultProps"
      :expand-on-click-node="false"
      :default-expanded-keys="defaultExpandedKeys"
      @node-drop="handleDrop"
      draggable
      :allow-drop="allowDrop"
      :allow-drag="allowDrag"
      node-key="catId"
      ref="tree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="data.catLevel <= 2"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            Append
          </el-button>
          <el-button
            v-if="childrenNum(data)==0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>
          <el-button type="text" size="mini" @click="() => edit(data)">
            edit
          </el-button>
          <!-- <el-button type="text" size="mini" @click="() => count(node)">
            count
          </el-button> -->
        </span>
      </span>
    </el-tree>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <el-form :model="catagory">
        <el-form-item label="分类名称">
          <el-input v-model="catagory.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCancel">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
/* eslint-disable */
export default {
  data() {
    return {
      tree: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      defaultExpandedKeys: [],
      dialogFormVisible: false,
      dialogTitle: "",
      catagory: {
        name: "",
        parentCid: 0,
        catLevel: 1,
        showStatus: 1,
        catId: 0,
      },
      saveShow: false,
      saveData: [],
    };
  },
  created: function () {
    console.log("loading product category tree....");
    this.getTree();
  },
  components: {},
  activated() {},
  methods: {
    deleteBatch(){
      var checkNodes = this.$refs.tree.getCheckedNodes();
      if(checkNodes.length<=0){
        return
      }
      var ids = []
      for(var i=0;i<checkNodes.length;i++){
        ids.push(checkNodes[i].catId)
      }
      console.log(ids)
      this.$confirm(`确定删除【${checkNodes[0].name}】等${checkNodes.length}个分类吗?`)
        .then((_) => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            if (data.msg == "success") {
              this.getTree();
            }
          });
        })
        .catch((_) => {});
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log("tree drop: ", dropNode.label, dropType);
      this.saveShow = true;
      var catLevel=0
      var parentCid=0
      
      if (dropType == "before" || dropType == "after") {
        catLevel = dropNode.data.catLevel;
        parentCid = dropNode.data.parentCid;
      } else if (dropType == "inner") {
        parentCid = dropNode.data.catId;
        catLevel = dropNode.data.catLevel+1;
      } else{
        return
      }
      console.log('catLevel:',catLevel,'parentCid:',parentCid)
      draggingNode.data.parentCid=parentCid
      var {data} = draggingNode
      if(data.catLevel!=catLevel){
        this.updateLevel(data,catLevel)
      }
      
      for(var i=0;i<this.saveData.length;i++){
        if(this.saveData[i].catId==draggingNode.data.catId){
          this.saveData.splice(i,1)
          break
        }
      }
      this.saveData.push(draggingNode.data)
      console.log(this.saveData)
    },
    childrenNum(data) {
      return (data.children==null)?0:data.children.length;
    },
    updateLevel(data,level) {
      data.catLevel=level
      for(var i=0;i<this.childrenNum(data);i++){
        this.updateLevel(data.children[i],level+1)
      }
    },
    allowDrop(draggingNode, dropNode, type) {
      var level = this.countLevel(draggingNode);
      if (type == "prev" || type == "next") {
        return level + dropNode.data.catLevel - 1 <= 3;
      } else if (type == "inner") {
        return level + dropNode.data.catLevel <= 3;
      } else {
        return false;
      }
    },
    allowDrag(draggingNode) {
      return true;
    },
    count(node) {
      console.log("node:", node);
      var { data } = node;
      var maxLevel = this.maxLevel(data);
      var level = maxLevel - data.catLevel + 1;
    },
    maxLevel(data) {
      var maxLevel = data.catLevel;
      for (var i = 0; i < this.childrenNum(data); i++) {
        var level = this.maxLevel(data.children[i]);
        if (level > maxLevel) {
          maxLevel = level;
        }
      }
      return maxLevel;
    },
    countLevel(node) {
      var { data } = node;
      var maxLevel = this.maxLevel(data);
      return maxLevel - data.catLevel + 1;
    },
    splitSaveData() {
      var array = []
      for(var i=0;i<this.saveData.length;i++){
        this.splitCategory(this.saveData[i],array)
      }
      console.log('saveArray',array)
      return array
    },
    splitCategory(data,array){
      var {catId,parentCid,catLevel}=data
      for(var i=0;i<array.length;i++){
        if(array[i].catId==catId){
          array.splice(i,1)
          break
        }
      }
      array.push({catId,parentCid,catLevel})
      for(var i=0;i<this.childrenNum(data);i++){
        this.splitCategory(data.children[i],array)
      }
    },
    save() {
      console.log("save");
      this.$http({
        url: this.$http.adornUrl("/product/category/updateBatch"),
        method: "post",
        data: this.$http.adornData(this.splitSaveData(), false),
      }).then(({ data }) => {
        if (data.msg == "success") {
          this.getTree();
          this.saveShow = false;
          this.saveData = [];
        }
      });
    },
    cancel() {
      console.log("cancel");
      this.saveShow = false;
      this.getTree();
      this.saveData = [];
    },
    // 拖拽相关-----------------------<
    dialogCancel() {
      this.dialogFormVisible = false;
      this.clearcatagory();
    },
    clearcatagory() {
      this.catagory = {
        name: "",
        parentCid: 0,
        catLevel: 1,
        showStatus: 1,
        catId: 0,
      };
    },
    editCategory() {
      var { name, catId } = this.catagory;
      this.dialogFormVisible = false;
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData({ name, catId }, false),
      }).then(({ data }) => {
        if (data.msg == "success") {
          this.getTree();
          this.defaultExpandedKeys = [this.catagory.parentCid];
          this.clearcatagory();
        }
      });
    },
    addCategory() {
      var { name, parentCid, catLevel, showStatus } = this.catagory;
      this.dialogFormVisible = false;
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(
          { name, parentCid, catLevel, showStatus },
          false
        ),
      }).then(({ data }) => {
        if (data.msg == "success") {
          this.getTree();
          this.defaultExpandedKeys = [this.catagory.parentCid];
          this.clearcatagory();
        }
      });
    },

    submitData() {
      if (this.submitType == "add") {
        this.addCategory();
      } else if (this.submitType == "edit") {
        this.editCategory();
      }
    },

    edit(data) {
      console.log("edit ", data);
      this.dialogFormVisible = true;
      this.submitType = "edit";
      this.dialogTitle = "编辑分类";
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get",
      }).then(({ data }) => {
        console.log("get data", data);
        var { category } = data;
        console.log("get category", category);
        this.catagory.name = category.name;
        this.catagory.parentCid = category.parentCid;
        this.catagory.catLevel = category.catLevel;
        this.catagory.showStatus = category.showStatus;
        this.catagory.catId = category.catId;
      });
    },

    append(data) {
      console.log("append ", data);
      this.dialogFormVisible = true;
      this.submitType = "add";
      this.dialogTitle = "追加分类";
      this.catagory.parentCid = data.catId;
      this.catagory.catLevel = data.catLevel * 1 + 1;
      this.catagory.showStatus = 1;
    },

    remove(node, data) {
      console.log("remove ", node, data);
      var ids = [data.catId];
      this.$confirm(`确定删除【${data.name}】分类?`)
        .then((_) => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            if (data.msg == "success") {
              this.getTree();
              this.defaultExpandedKeys = [node.parent.data.catId];
            }
          });
        })
        .catch((_) => {});
    },

    getTree() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        this.tree = data.data;
        console.log("get data success:", this.tree);
      });
    },
  },
};
</script>
